<template>
  <div>
    <!-- 导航栏 -->
    <van-nav-bar title="搜索中心" left-arrow @click-left="onClickLeft" />
    <!-- 搜索框 -->
    <form action="/">
      <van-search
        v-model.trim="keyWord"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @input="onInput"
      />
    </form>
    <!-- 历史记录 -->
    <van-cell-group>
      <van-cell title="历史记录" v-show="!sugShow" />
      <van-cell
        v-for="(item, index) in history"
        :key="index"
        :title="item"
        v-show="!sugShow"
      />
      <!-- 模糊匹配 -->
      <van-cell
        v-for="(item, index) in suggestion"
        :key="index + '-only'"
        v-show="sugShow"
      >
        <div v-html="lineHeight(item)"></div>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { setHistory, getHistory } from '@/utils/storage'
import { suggestionAPI } from '@/api'
export default {
  name: 'mySearch',
  data () {
    return {
      keyWord: '',
      history: [],
      suggestion: [],
      sugShow: false,
      newSug: []
    }
  },
  created () {
    this.history = getHistory() || []
  },
  computed: {},
  methods: {
    onClickLeft () {
      this.$router.go(-1)
    },
    lineHeight (text) {
      const hilightSearchStr = `<span class="active">${this.keyWord}</span>` // 高亮的字符
      const reg = new RegExp(this.keyWord, 'ig') // 正则表达式
      return text.replaceAll(reg, hilightSearchStr)
    },
    onSearch () {
      this.$toast(this.keyWord)
      if (!this.history.includes(this.keyWord)) {
        this.history.push(this.keyWord)
        setHistory(this.history)
      }
      this.$router.push(`/search/result/${this.keyWord}`)
    },
    onCancel () {
      this.$toast('取消')
      this.sugShow = false
    },
    // 搜索联想
    async onInput () {
      if (this.keyWord !== '') {
        const res = await suggestionAPI({
          q: this.keyWord
        })
        if (res.data.data.options[0]) {
          this.suggestion = res.data.data.options
        }
        this.sugShow = true
        // console.log(this.suggestion)
      }
    }
  }
}
</script>

<style lang="less" scoped>
::v-deep .active {
  color: #f00;
}
</style>
